package com.yuanjun.product.controller.front;

import com.alibaba.fastjson.JSON;
import com.yuanjun.product.entity.JczUser;
import com.yuanjun.product.service.AddressService;
import com.yuanjun.product.vo.base.BaseResult;
import com.yuanjun.product.vo.common.Const;
import com.yuanjun.product.vo.req.AddressReq;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

@Slf4j
@RestController
@RequestMapping(value = "/address")
public class AddressController {
    @Resource
    private AddressService addressService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 查询该用户所有收获地址
     * @param token
     * @return
     */
    @RequestMapping("/findAll")
    public BaseResult findAddress(@RequestHeader(Const.PROFRONTTOKEN) String token){
        log.info("token:{},param:{}", token);
        String userJson = stringRedisTemplate.opsForValue().get(token);
        JczUser user = JSON.parseObject(userJson, JczUser.class);
        return BaseResult.createOk(addressService.findAddress(user.getId()));
    }

    /**
     * 新增收获地址
     * @param addressReq
     * @return
     */
    @RequestMapping("/insert")
    public BaseResult insertAddress(@RequestHeader(Const.PROFRONTTOKEN) String token,@RequestBody AddressReq addressReq){
        String userJson = stringRedisTemplate.opsForValue().get(token);
        JczUser user = JSON.parseObject(userJson, JczUser.class);
        addressReq.setUserId(user.getId());
        return BaseResult.createOk(addressService.insertAddress(addressReq));
    }

    /**
     * 加载对应收获地址信息
     * @param id
     * @return
     */
    @RequestMapping("/load")
    public BaseResult loadAddress(@RequestParam Integer id){
        return BaseResult.createOk(addressService.loadAddress(id));
    }

    /**
     * 修改对应收获地址信息
     * @param addressReq
     * @return
     */
    @RequestMapping("/update")
    public BaseResult updateAddress(@RequestHeader(Const.PROFRONTTOKEN) String token,@RequestBody AddressReq addressReq){
        String userJson = stringRedisTemplate.opsForValue().get(token);
        JczUser user = JSON.parseObject(userJson, JczUser.class);
        addressReq.setUserId(user.getId());
        return BaseResult.createOk(addressService.updateAddress(addressReq));
    }

    /**
     * 删除收获地址
     * @param id
     * @return
     */
    @RequestMapping("/delete")
    public BaseResult deleteAddress(@RequestParam Integer id){
        return BaseResult.createOk(addressService.deleteAddress(id));
    }

}
